package com.wh.influxdb.service.impl;

import com.influxdb.client.domain.WritePrecision;
import com.wh.influxdb.common.core.InfluxdbTemplate;
import com.wh.influxdb.domain.query.PageQuery;
import com.wh.influxdb.measurement.Stress;
import com.wh.influxdb.service.IStressService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: xu
 * @Date: 2025/1/14
 * @Description: 应力监测
 **/
@Service
public class StressServiceImpl implements IStressService {

    @Resource
    private InfluxdbTemplate influxdbTemplate;

    @Override
    public Stress queryLastRow() {
//        String query = " |> range(start: -1h) " +
//                       " |> last() " +
//                       " |> yield(name: \"last\")";
        String flux = String.format("from(bucket: \"%s\") " +
                "|> range(start: -1h) " +
                "|> filter(fn: (r) => r[\"_measurement\"] == \"%s\") "+
                "|> last() " +
                "|> yield(name: \"last\") ", "fusion", "stress"
        );
        List<Stress> ms = influxdbTemplate.queryMByFlux(flux, Stress.class);
        if (!ms.isEmpty()) {
            return ms.get(0);
        }
        return null;
    }

    @Override
    public void stressInsert(Stress stress) {
        System.out.println("插入应力时序数据！！！！！！");
        if (stress == null) {
            stress = new Stress();
        }
        stress.setTime(Instant.now());
        stress.setS1(1203.23F);
        stress.setS2(6858.71F);
        stress.setR1(1447.7624F);
        stress.setR2(7.1F);
        stress.setSName("S5-E12");
        influxdbTemplate.insert(WritePrecision.S, stress);
    }

    @Override
    public void batchInsert(List<?> entity) {
        influxdbTemplate.batchInsert(WritePrecision.S,entity);
    }

    @Override
    public void insert(Object entity) {

    }

    @Override
    public void pageList(PageQuery pageQuery) {

    }
}
